package com.prs.crm.action.base;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.courser.ui.TreeNode;

import com.prs.crm.domain.District;
import com.prs.crm.domain.sys.Code;
import com.prs.crm.domain.sys.CodeCommon;
import com.prs.crm.service.DistrictService;
import com.prs.crm.service.sys.CodeCommonService;
import com.prs.crm.service.sys.CodeService;

public class DistrictAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private DistrictService districtService;

	private PaginationSupport pagination;

	private District district;

	private District parentDistrict;

	private Collection<TreeNode> nodes;
	private CodeCommon codeCommon;
	private CodeCommonService codeCommonService;
	private String Encode;
	private Code code;
	private CodeService codeService;
	private Collection<CodeCommon> codelist;

	public void setDistrictService(DistrictService districtService) {
		this.districtService = districtService;
	}

	public DistrictService getDistrictService() {
		return districtService;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setDistrict(District district) {
		this.district = district;
	}

	public District getDistrict() {
		return district;
	}

	public void setParentDistrict(District parentDistrict) {
		this.parentDistrict = parentDistrict;
	}

	public District getParentDistrict() {
		return parentDistrict;
	}

	public void setNodes(Collection<TreeNode> nodes) {
		this.nodes = nodes;
	}

	public Collection<TreeNode> getNodes() {
		return nodes;
	}

	@Action("setDistrict")
	public String setDistrict() {
		this.codelist = this.getCodeCommonService().getCodeCommonByCodeType(
				"地区");
		return SUCCESS;
	}

	@Action(value = "loadDistrict", results = { @Result(name = "success", type = "json", params = {
			"root", "district", "excludeProperties", "childs" }) })
	public String loadDistrict() {
		return SUCCESS;
	}

	/**
	 * 载入地区树 TreeNode 本身就是一个树形结构,一个TreeNode可以包含若干子结点, TreeNode中的 item属性就是一个子结点链表
	 * 
	 * @return
	 */
	@Action(value = "loadDistrictTree", results = { @Result(name = "success", type = "json", params = {
			"root", "nodes" }) })
	public String loadDistrictTree() {
		nodes = new ArrayList<TreeNode>();// 存放第一级城市的结点，其他地区是这些第一级地区的子结点
		Collection<District> districts = this.getDistrictService().getRootDistricts();// 查询所有的一级城市
		for (District district : districts) {
			TreeNode node = new TreeNode();
			node.setId(district.getId().toString());// 每个树结点都有一个唯一的ID号，一般这个ID号就是数据记录的编号
			node.setText(district.getName());// 结点需要显示的文本，这里显示地区的名称
			nodes.add(node);
			addChildNode(district, node);// 添加子级地区
		}
		return SUCCESS;
	}

	private void addChildNode(District parent, TreeNode parentNode) {
		/**
		 * 如果存在子结点地区
		 */
		if (parent.getChilds() != null) {
			/**
			 * 循环获取子地区
			 */
			for (District district : parent.getChilds()) {
				TreeNode node = new TreeNode();// 构建子地区结点
				node.setId(district.getId().toString());
				node.setText(district.getName());
				parentNode.addChildNode(node);// 将子地区结点加入父地区结点中，调用treeNode的addChildNode方法
				addChildNode(district, node);
			}
		}
	}

	@Action(value = "saveDistrict", results = {
			@Result(name = "success", type = "json", params = { "root",
					"district", "excludeProperties", "childs,parent" }),
			@Result(name = "error", type = "chain", location = "setDistrict") })
	public String saveDistrict() {
		if (district.getName() == null || "".equals(district.getName().trim())) {
			addActionError("地区名称不能为空");
			return ERROR;
		}
		if (district.getDistrictcode() == null
				|| "".equals(district.getDistrictcode().trim())) {
			addActionError("编码不能为空");
			return ERROR;
		}
		try {
			if (district.getId() == null) {
				if ("n".equals(Encode)) {
					int EncodeRplice = this.getCodeService().getBackRpliceAll("手动编码",
							"地区", district.getDistrictcode());
					if (EncodeRplice != 0) {
						this.addActionError("编码重复!请重新输入");
						return ERROR;
					}
				}
				if ("n".equals(Encode)) {
					Code codes = new Code();
					codes.setCodeValue(district.getDistrictcode());
					codes.setEntityName(this.getClass().getName());
					codes.setCodeType("手动编码");
					codes.setCodeMolde("地区");
					this.getCodeService().save(codes);
					district.setCode(codes);
					district.setParent(parentDistrict);
				} else {
					CodeCommon Vob = this.getCodeCommonService().getVobject(
							codeCommon.getId());
					Code codes = new Code();
					codes.setEntityName(this.getClass().getName());
					codes.setCodeValue(district.getDistrictcode());
					Vob.setNumBackUp(Increase(Vob.getNumBackUp()));
					this.codeCommonService.saveOrUpdate(Vob);
					codes.setCodeType(Vob.getCodePlan());
					codes.setCodeMolde("地区");
					this.getCodeService().save(codes);
					district.setCode(codes);
					district.setParent(parentDistrict);
					
				}
			}
			this.getDistrictService().save(district);
		} catch (Exception e) {
			this.setDistrict(null);
		}
		
		return SUCCESS;
	}

	@Action(value = "removeDistrict", results = { @Result(name = "success", type = "json", params = {
			"root", "prompt" }) })
	public String removeDistrict() {
		try {
			this.getDistrictService().remove(district);
			this.setPrompt("success");
		} catch (Exception e) {
			this.setPrompt("error");
		}
		return SUCCESS;
	}

	@Action("viewDistrict")
	public String view() {
		return SUCCESS;
	}

	public CodeCommon getCodeCommon() {
		return codeCommon;
	}

	public void setCodeCommon(CodeCommon codeCommon) {
		this.codeCommon = codeCommon;
	}

	public CodeCommonService getCodeCommonService() {
		return codeCommonService;
	}

	public void setCodeCommonService(CodeCommonService codeCommonService) {
		this.codeCommonService = codeCommonService;
	}

	public String getEncode() {
		return Encode;
	}

	public void setEncode(String encode) {
		Encode = encode;
	}

	public Code getCode() {
		return code;
	}

	public void setCode(Code code) {
		this.code = code;
	}

	public CodeService getCodeService() {
		return codeService;
	}

	public void setCodeService(CodeService codeService) {
		this.codeService = codeService;
	}

	public Collection<CodeCommon> getCodelist() {
		return codelist;
	}

	public void setCodelist(Collection<CodeCommon> codelist) {
		this.codelist = codelist;
	}

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public static String Increase(String backupNum) {
		String Inc = "";
		int lengths = backupNum.length();
		String lengthss = (Integer.parseInt(backupNum) + 1) + "";
		int increase = (lengthss.trim()).length();
		if (lengths != increase) {
			String In = "";
			for (int i = 0; i < lengths - increase; i++) {
				In = In + "0";
			}
			In = (In + lengthss).trim();
			Inc = In;
		} else {
			Inc = lengthss;
		}
		return Inc.trim();
	}

}
